package net.seabookchen.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.seabookchen.service.UserIdentificationService;

public class AccessControlFilter implements Filter {

	private static final Logger log = Logger
			.getLogger(AccessControlFilter.class.getName());
	private String requestAction = "GET";
	private List<String> byPassUrls = null;

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		
		String uri = req.getRequestURI();
		String action = req.getMethod();
		log.info("AccessControlFilter action: " + action + " uri:" + uri);

		boolean byPass = false;
		if (UserIdentificationService.isAdminLoggedIn()) {
			byPass = true;
		}
		
		if (action.equalsIgnoreCase(requestAction)) {
			byPass = true;
		}
		
		for (String regex : byPassUrls) {
			if (uri.matches(regex)) {
				byPass = true;
				break;
			}
		}
		
		if (!byPass) {
			resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You are not authorized!");
			return;
		}

		filterChain.doFilter(req, resp);
	}

	@Override
	public void init(FilterConfig fc) throws ServletException {
		String byPassUrl = fc.getInitParameter("byPassUrl");
		this.byPassUrls  = Arrays.asList(byPassUrl.split(","));
	}

}
